import router from "@/router/index"
import store from "@/store"
import {generateRoutes} from "@/util";
import { getToken } from '@/util/auth'
 
// 检查是否存在于免登陆白名单
function inWhiteList(toPath) {
    const whiteList = ['/login', '/404']
    const path = whiteList.find((value) => {
        // 使用正则匹配
        const reg = new RegExp('^' + value)
        return reg.test(toPath)
    })
    return !!path
}
 
router.beforeEach((to, from, next) => {
    console.group('%c%s', 'color:blue', `${new Date().getTime()}  ${to.path} 的全局前置守卫----------`)
    console.log('所有活跃的路由记录列表', router.getRoutes())
    console.groupEnd()
    const token = getToken()
    let isLoadRouters = store.state.isLoadRouters
    if (inWhiteList(to.path)) {
        next()
    } else {
        //用户已登录
        if (token && JSON.stringify(store.getters.GET_MENULIST) !== '[]') {
            if (isLoadRouters) {
                // console.log('路由已添加，直接跳转到目标页面');
                next()
            } else {
                //解决刷新页面空白
                //console.log('重新加载路由，并跳转到目标页');
                let menuList = store.getters.GET_MENULIST
                store.commit('SET_ISLOADROUTERS', true)
                //添加动态路由
                generateRoutes(menuList)
 
                next({...to, replace: true})
            }
        } else {
            // console.log('无登录信息，跳转到登录页');
            store.commit('SET_ISLOADROUTERS', false)
            next(`/login`)
        }
    }
 
})